﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;

using Leadtools;
using Leadtools.Codecs;
using Leadtools.WinForms;

using System.Runtime.InteropServices;
using System.Collections;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using Leadtools.ImageProcessing;
using System.Runtime.InteropServices;
using DevExpress.XtraPrinting;
using ShellDll;
using System.Threading;
using MINERP.BLL.Common;

namespace MINERP.CustomerManage.PickupPhoto
{
    public partial class FrmDisposeMain : Form
    {
        //属性
        public int UserId { get; set; }
        private static FrmDisposeMain _instance;
        public static FrmDisposeMain GetInstance(int inUserID)
        {
            //get
            //{
            if (_instance == null)
            {
                _instance = new FrmDisposeMain(inUserID);
            }
            return _instance;
            //}
            //set
            //{
            //    _instance = value;
            //}
        }

        //参数
        private BLL.CustomerManage.DisposePhotoBLL bll = new MINERP.BLL.CustomerManage.DisposePhotoBLL();

        public string StartOrderTotalPath;                  //等待开单总路径
        public string DisposeTotalPath;                     //员工理件的总路径
        private DataTable AllShop;
        private DataTable AllUser;                          //所有员工
        private TreeNode prePhotoNode;                      //点击节点，加载节点内照片时，判断当前节点是否与上一节点相等，相等就不用再加载
        public string SelectedShopName;                     //保存整理好的文件夹时，选中的商户名称
        public int SelectedShopId;                          //保存整理好的文件夹时，选中的商户Id
        public string SelectedUserName;                     //保存整理好的商户时，选中的开单员名称
        public int SelectedUserId;                          //保存整理好的商户时，选中的开单员Id
        private string CurrUserName;
        public bool isLoad = false;
        public double NewHeight;                            //照片修改后的新高(修改高宽使用)
        public double NewWidth;                             //照片修改后的新宽(修改高宽使用)
        private bool ExAddPhoto = false;                    //强制加载文件夹内的照片(在修改了照片的高宽后)

        string StandardUnit = "";                           //修改照片尺寸的标准单位
        double StandardHeight = 0;                          //修改照片尺寸的标准高宽
        double StandardWidth = 0;
        private string picTag = ".JPEG.JPG.TIF.BMP.TIFF";          //图片文件标志
        private string CurrSelectPath = "";                   //记录当前选择路径
        private bool IsNeedReload = false;                   //是否要重新读取文件信息
        private string RootPath = "";//总目录
        private bool IsExPickupDir = true;

        private bool DisplayMode = false;                   //false照片列表 true缩略图     
        private RasterThumbnailBrowser browser = new RasterThumbnailBrowser();      //缩略图容器
        public string photoNewName = "";
        private List<FileAttribute> ListFileCache = new List<FileAttribute>();///存储产看过的文件，保存时清空
        private List<FileAttribute> ListFileDisplay = new List<FileAttribute>();///显示照片列表文件    
        private List<FileAttribute> ListFileDrog = new List<FileAttribute>();///拖拽照片列表文件    

        ///
        #region API
        //API
        /// <summary>
        /// 移动文件，文件夹
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dst"></param>
        /// <param name="flag">1如果文件存在，则替换；2如移动到不同的卷，则复制文件并删除原来的文件；3移动操作在系统重启后才真正执行</param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "MoveFileEx", CharSet = CharSet.Unicode)]
        public static extern bool MoveFile(string src, string dst, long flag);

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "CreateDirectory")]
        public static extern bool CreateDirectory(string path);

        /// <summary>
        /// 移除文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "RemoveDirectory")]
        public static extern bool RemoveDirectory(string path);

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "DeleteFile")]
        public static extern bool DelFile(string path);

        /// <summary>
        /// 打开文件夹
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="lpszOp"></param>
        /// <param name="lpszFile"></param>
        /// <param name="lpszParams"></param>
        /// <param name="lpszDir"></param>
        /// <param name="FsShowCmd"></param>
        /// <returns></returns>
        [DllImport("shell32.dll", EntryPoint = "ShellExecute")]
        public static extern int OpenFolder(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
        #endregion

        public FrmDisposeMain(int inUserid)
        {
            InitializeComponent();
            //StartOrderTotalPath = @"\\server1\Server上的文件备份\照片目录\等待开单";
            //browser1.StartUpDirectory = FileBrowser.SpecialFolders.Other;
            //browser1.StartUpDirectoryOther = StartOrderTotalPath;
            //browser1.StartUpDirectoryOther = @"y:";
            //UserId = 3;
            //StartOrderTotalPath = @"\\server1\Server上的文件备份\照片目录\等待开单";            //等待开单总路径
            DisposeTotalPath = Convert.ToString((bll.GetUser(inUserid)).Rows[0]["DisposePhotoPath"]); //取得员工理件的总路径，在将理好件的文件夹转移到等待开单的时候使用  
            CurrUserName = Convert.ToString((bll.GetUser(inUserid)).Rows[0]["UserName"]);
            if (!string.IsNullOrEmpty(DisposeTotalPath))
            {
                browser1.StartUpDirectoryOther = StartOrderTotalPath;
                browser1.StartUpDirectoryOther = @"V:";
                //CreatNetConn("V", DisposeTotalPath);
            }
            else
            {
                IsExPickupDir = false;
            }
            ;

        }

        private void FrmDisposeMain_Load(object sender, EventArgs e)
        {
            //测试

            gridViewListView.OptionsView.AllowCellMerge = true;
            gridViewListView.Appearance.HorzLine.BackColor = Color.Black;
            gridViewListView.Appearance.VertLine.BackColor = Color.Black;

            gridViewListView.CellMerge += new CellMergeEventHandler(gridViewListView_CellMerge);
            //     CreatNetConn();//创建网络映射
            if (!IsExPickupDir)
            {
                ShowMsg("请先设置理件目录");
            }
            RootPath = StartOrderTotalPath.Substring(0, StartOrderTotalPath.LastIndexOf("\\")) + "\\理件";//构建理件目录
            isLoad = true; //browser
            //加载商户
            AllShop = bll.GetShops();               //所有有效的商户
            BindShop(AllShop);
            //加载员工
            BindUser();
            // AddTree();
            //设置缩略图的拖曳操作
            RegBrowserEvent();
            // browser1.SelectPath(StartOrderTotalPath, true);
            //browser1.StartUpDirectory = FileBrowser.SpecialFolders.Other;
            //browser1.StartUpDirectoryOther = StartOrderTotalPath;
            //browser1.StartUpDirectoryOther = @"Y:";
            spcSecond.Panel1Collapsed = true;       //点击后关闭
            tsCloseShop.Text = "展开选择商户&R";
            tsCloseShop.Image = Properties.Resources.OpenDirectory;
            toolStripTextBoxDisplayFloor.Text = Properties.Settings.Default.IntFloorNum.ToString();
            _CheckDPI = Properties.Settings.Default.CheckDPI;
        }

        void InitPath()
        {

        }

        ///// <summary>
        ///// 显示信息
        ///// </summary>
        ///// <param name="msg"></param>
        private void ShowMsg(string msg)
        {
            MessageBox.Show(msg, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        /// <summary>
        /// 绑定商户
        /// </summary>
        private void BindShop(DataTable shops)
        {
            try
            {
                lbShop.DisplayMember = "ShopName";
                lbShop.ValueMember = "ShopId";
                lbShop.DataSource = shops;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 绑定员工
        /// </summary>
        private void BindUser()
        {
            try
            {
                DataTable dt = bll.GetUsers();
                AllUser = dt;
                /*
                cbUsers.DisplayMember = "UserName";
                cbUsers.ValueMember = "UserId";
                cbUsers.DataSource = dt;
                cbUsers.SelectedValue = UserId;                 //默认的开单员是当前员工*/
                //lblStartOrder.Text = dt.Select("UserId=" + UserId).First()["UserName"].ToString();
                //lblStartOrder.Tag = UserId;
                SelectedUserId = UserId;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        ////-------------------数据结构--------------
        ///// <summary>
        ///// 文件夹路径类
        ///// </summary>
        //private class FolderCL
        //{
        //    public bool IsRoot;                 //是否是根节点
        //    public string FolderName;           //文件夹名称
        //    public string Path;                 //路径(根节点保留全路径，其他节点只保留当前路径)
        //    public int Level;                   //文件夹处于第几层
        //}

        /// <summary>
        /// 照片结构
        /// </summary>
        private class FileAttribute
        {
            public string FileName { get; set; }        //照片名字
            public double Height { get; set; }          //高
            public double Width { get; set; }           //宽
            public int HeightPix { get; set; }          //像素高
            public int WidthPix { get; set; }           //像素宽
            public string HWcm { get; set; }            //高×宽(cm)
            public string HWin { get; set; }            //高×宽(in)
            public int DPI { get; set; }                //DPI
            public string FullName { get; set; }   //照片全路径
            public int Rank { get; set; }               //照片级别(双击时筛选不符合尺寸条件时使用)
            public RasterImageListItem Thumb { get; set; }      //缩略图
            public RasterImage Image { get; set; }      //缩略图
            public bool IsPic { get; set; }//是否图片
            public string fileContext { get; set; }
        }
        #region 创建网络映射
        [StructLayout(LayoutKind.Sequential)]
        public struct NETRESOURCEA
        {
            public int dwScope;
            public int dwType;
            public int dwDisplayType;
            public int dwUsage;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpLocalName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpRemoteName;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpComment;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpProvider;
            public override String ToString()
            {
                String str = "LocalName:   " + lpLocalName + "   RemoteName:   " + lpRemoteName
                + "   Comment:   " + lpComment + "   lpProvider:   " + lpProvider;
                return (str);
            }
        }


        [DllImport("mpr.dll")]
        public static extern int WNetAddConnection2A(
        [MarshalAs(UnmanagedType.LPArray)]   NETRESOURCEA[] lpNetResource,
        [MarshalAs(UnmanagedType.LPStr)]   string lpPassword,
        [MarshalAs(UnmanagedType.LPStr)]   string UserName,
        int dwFlags);

        private bool CreatNetConn(string inName, string inPath)
        {
            NETRESOURCEA[] n = new NETRESOURCEA[1];
            n[0] = new NETRESOURCEA();
            n[0].dwType = 1;
            int dwFlags = 1;
            n[0].lpLocalName = inName;
            n[0].lpRemoteName = inPath;
            n[0].lpProvider = null;
            // Console.WriteLine(n[0]);

            int res = WNetAddConnection2A(n, null, null, dwFlags);
            if (res != 0)
            {
                return false;
            }
            else
            {
                return true;
            }



        }
        [DllImport("NetAp32.dll", CharSet = CharSet.Unicode)]
        extern static int NetShareDel(string strserver, string strshare, int reserved);

        #endregion


        private void tsCloseShop_Click(object sender, EventArgs e)
        {
            if (!spcSecond.Panel1Collapsed)             //商户选择本身是展开的
            {
                spcSecond.Panel1Collapsed = true;       //点击后关闭
                tsCloseShop.Text = "展开选择商户&R";
                tsCloseShop.Image = Properties.Resources.OpenDirectory;
            }
            else
            {
                spcSecond.Panel1Collapsed = false;      //点击后展开
                tsCloseShop.Text = "关闭选择商户&R";
                tsCloseShop.Image = Properties.Resources.close;
            }
        }
        /// <summary>
        /// 浏览不同文件夹记文件并显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void browser1_SelectedFolderChanged(object sender, FileBrowser.SelectedFolderChangedEventArgs e)
        {

            if (!isLoad)
            {
                return;
            }



            CurrSelectPath = e.Path;
            // ShowMsg(CurrSelectPath);
            //gcPhotoHW.DataSource = null;
            //gcPhotoHW.RefreshDataSource();
            // DisplayPickuped(CurrSelectPath);
            //if (ListSizeNum.Count > 0)
            //{

            //    DisplayTables(IsAutoAnlyse);
            //}
            
                if (CurrSelectPath.ToUpper().IndexOf("V:") > -1)
                {
                    if (CurrSelectPath.ToUpper().Equals("V:"))
                    {

                    }
                    else
                    {
                        DisplayTables(IsAutoAnlyse);
                    }
                }
            
        }
        /// <summary>
        /// 获取文件信息显示用
        /// </summary>
        /// <param name="inDirPath"></param>
        public void GetDirInfo(string inDirPath)
        {
            ListFileDisplay = new List<FileAttribute>();
            if (!Directory.Exists(inDirPath))
            {
                return;
            }
            DirectoryInfo directoryInfo = new DirectoryInfo(inDirPath);
            FileInfo[] fileArrInfo = directoryInfo.GetFiles();
            if (fileArrInfo.Count() < 0)
            {

            }
            else
            {
                RasterCodecs.Startup();
                RasterCodecs codecs = new RasterCodecs();


                foreach (FileInfo fileInfo in fileArrInfo)
                {
                    FileAttribute fa = ListFileCache.FirstOrDefault(p => p.FullName == fileInfo.FullName);
                    if (fa != null)
                    {
                        ListFileDisplay.Add(fa);
                        continue;
                    }

                    #region 识别文件类型添加缓冲文件集合和显示集合
                    FileAttribute file = new FileAttribute();
                    if (picTag.Contains(fileInfo.Extension.ToUpper()))
                    {
                        CodecsImageInfo img = codecs.GetInformation(fileInfo.FullName, true);
                        //RasterImage a = codecs.Load(fileInfo.FullName);

                        file.DPI = img.XResolution;
                        file.FileName = fileInfo.Name;
                        file.Height = img.Height;
                        file.Width = img.Width;
                        file.FullName = fileInfo.FullName;
                        file.Height = (double)img.Height / file.DPI;
                        file.Width = (double)img.Width / file.DPI;
                        file.HWcm = string.Format("{0:0.##}", file.Height * 2.54) + "×" + string.Format("{0:0.##}", file.Width * 2.54);
                        file.HWin = string.Format("{0:0.##}", file.Height) + "×" + string.Format("{0:0.##}", file.Width);
                        file.IsPic = true;
                        //file.Thumb=img.
                        ListFileCache.Add(file);
                        ListFileDisplay.Add(file);
                        //ListFileDisplay(file);
                    }
                    else if (".TXT".Equals(fileInfo.Extension.ToUpper()))
                    {
                        file.DPI = 0;
                        file.FileName = fileInfo.Name;
                        file.Height = 0;
                        file.Width = 0;
                        file.FullName = fileInfo.FullName;
                        file.Height = 0;
                        file.Width = 0;
                        file.HWcm = "";
                        file.HWin = "";
                        file.IsPic = false;
                        StreamReader reader = new StreamReader(fileInfo.FullName, System.Text.Encoding.GetEncoding("gb2312"));
                        file.fileContext = reader.ReadToEnd();
                        reader.Close();


                        ListFileCache.Add(file);
                        ListFileDisplay.Add(file);
                    }
                    else
                    {
                        //if (File.Exists(fileInfo.FullName))//只取文件
                        //{
                        //    file.DPI = 0;
                        //    file.FileName = fileInfo.Name;
                        //    file.Height = 0;
                        //    file.Width = 0;
                        //    file.FullName = fileInfo.FullName;
                        //    file.Height = 0;
                        //    file.Width = 0;
                        //    file.HWcm = "";
                        //    file.HWin = "";
                        //    file.IsPic = false;
                        //    ListFileCache.Add(file);
                        //    ListFileDisplay.Add(file);
                        //}
                    }
                    #endregion
                }

            }
            gcPhotoHW.DataSource = ListFileDisplay;
            gcPhotoHW.RefreshDataSource();
        }
        /// <summary>
        /// 显示文件夹下的文件
        /// </summary>
        /// <param name="inDirPath"></param>
        public void DisplayPickuped(string inDirPath)
        {
            ListFileDisplay = new List<FileAttribute>();
            if (!Directory.Exists(inDirPath))
            {
                return;
            }
            DirectoryInfo directoryInfo = new DirectoryInfo(inDirPath);
            FileInfo[] fileArrInfo = directoryInfo.GetFiles();
            if (fileArrInfo.Count() < 0)
            {

            }
            else
            {
                int falg = 0;//文件修改flag

                foreach (FileInfo fileInfo in fileArrInfo)
                {
                    FileAttribute fa = ListFileCache.FirstOrDefault(p => p.FullName == fileInfo.FullName);

                    if (fa != null)
                    {
                        ListFileDisplay.Add(fa);
                        falg++;
                    }

                }
                if (falg != 0 && falg < fileArrInfo.Count())
                {
                    GetDirInfo(CurrSelectPath);
                    //ShowMsg("该文件夹下文件有更新已经重新读取");

                }

            }
            DisplayPhoto();//显示图片
        }

        private void buttonShowPic_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                GetDirInfo(CurrSelectPath);
                SetPhotoGroup();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 照片按尺寸分组信息
        /// </summary>
        private void SetPhotoGroup()
        {
            try
            {
                lbPhotoGroup.Items.Clear();
                List<FileAttribute> photos = gcPhotoHW.DataSource as List<FileAttribute>;
                lbPhotoGroup.Items.Add("照片总数量：" + photos.Count(p => p.IsPic).ToString());
                Dictionary<string, int> groups = new Dictionary<string, int>();
                foreach (FileAttribute p in photos.Where(p => p.IsPic))
                {
                    if (groups.Keys.Contains(p.HWcm))
                    {
                        groups[p.HWcm]++;
                    }
                    else
                    {
                        groups.Add(p.HWcm, 1);
                    }
                }
                foreach (KeyValuePair<string, int> pair in groups)
                {
                    lbPhotoGroup.Items.Add(pair.Key + " 数量：" + pair.Value.ToString());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 修改照片尺寸的公共操作
        /// </summary>
        private void ModifyHWComman()
        {
            try
            {
                int[] indexes = gvPhotoHW.GetSelectedRows();
                List<int> indexes2 = new List<int>();
                foreach (int i in indexes)
                {
                    if (i >= 0)
                        indexes2.Add(i);
                }
                if (indexes2.Count > 0)
                {
                    FrmModifyHW frm = new FrmModifyHW();
                    frm.frm = this;
                    if (StandardUnit.Length == 0)
                    {
                        FileAttribute photo = gvPhotoHW.GetRow(indexes[0]) as FileAttribute;
                        frm.OldHeight = photo.Height;
                        frm.OldWidth = photo.Width;
                    }
                    else
                    {
                        frm.OldUnit = StandardUnit;
                        frm.OldHeight = StandardHeight;
                        frm.OldWidth = StandardWidth;
                    }
                    int oldPixH = 0;                        //原来的像素高
                    int oldPixW = 0;                        //原来的像素宽
                    int newPixH = 0;
                    int newPixW = 0;
                    if (DialogResult.OK == frm.ShowDialog())
                    {
                        RasterCodecs.Startup();
                        RasterCodecs codecs = new RasterCodecs();
                        CropCommand command = new CropCommand();
                        foreach (int index in indexes2)
                        {
                            FileAttribute p = gvPhotoHW.GetRow(index) as FileAttribute;
                            if (!p.IsPic)
                            {
                                continue;
                            }
                            if (p.Height <= NewHeight && p.Width <= NewWidth)           //小于或等于新高宽就不作操作
                            {
                                continue;
                            }
                            else
                            {
                                string path = p.FullName;
                                oldPixH = p.HeightPix;                                  //原来的像素
                                oldPixW = p.WidthPix;
                                newPixH = Convert.ToInt32(NewHeight * p.DPI);           //新像素
                                newPixW = Convert.ToInt32(NewWidth * p.DPI);
                                command.Rectangle = new Rectangle((oldPixW - newPixW) / 2, 0, newPixW, newPixH);
                                RasterImage img = codecs.Load(path);
                                command.Run(img);                   //裁照片
                                try
                                {
                                    codecs.Save(img, path, RasterImageFormat.Jpeg, 24);

                                }
                                catch
                                {
                                    FileInfo finfo = new FileInfo(path);                    //去掉只读属性，再试一次
                                    finfo.Attributes = FileAttributes.Normal;
                                    codecs.Save(img, path, RasterImageFormat.Jpeg, 24);
                                }
                                p.HeightPix = img.Height;
                                p.WidthPix = img.Width;
                                // p.FullName = p.FullName;
                                p.Height = (double)img.Height / p.DPI;
                                p.Width = (double)img.Width / p.DPI;
                                p.HWcm = string.Format("{0:0.##}", p.Height * 2.54) + "×" + string.Format("{0:0.##}", p.Width * 2.54);
                                p.HWin = string.Format("{0:0.##}", p.Height) + "×" + string.Format("{0:0.##}", p.Width);

                            }

                        }
                        codecs.Dispose();
                        RasterCodecs.Shutdown();
                        //重新加载
                        gcPhotoHW.RefreshDataSource();

                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 裁片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsModifyHW_Click(object sender, EventArgs e)
        {
            ModifyHWComman();
        }
        /// <summary>
        /// 切换视图和数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsExchange_Click(object sender, EventArgs e)
        {
            try
            {
                if (gcPhotoHW.DataSource == null)
                    return;
                Cursor = Cursors.WaitCursor;
                List<FileAttribute> photos = gcPhotoHW.DataSource as List<FileAttribute>;
                List<FileAttribute> selectedPhotos = new List<FileAttribute>();
                if (DisplayMode)                    //当前显示的是缩略图
                {
                    RasterImageListItemCollection selectedThumbs = browser.SelectedItems;
                    foreach (RasterImageListItem item in selectedThumbs)
                    {
                        selectedPhotos.Add((FileAttribute)item.Tag);
                    }
                    pPhotoDetail.Controls.Clear();
                    pPhotoDetail.Controls.Add(gcPhotoHW);
                    gvPhotoHW.ClearSelection();
                    for (int i = 0; i < gvPhotoHW.RowCount; i++)
                    {
                        FileAttribute pp = (FileAttribute)gvPhotoHW.GetRow(i);
                        if (selectedPhotos.Contains(pp))
                            gvPhotoHW.SelectRow(i);
                    }
                    DisplayMode = false;
                }
                else                                //当前显示的是列表
                {
                    int[] indexes = gvPhotoHW.GetSelectedRows(); //当前选中的照片
                    foreach (int index in indexes)
                    {
                        FileAttribute pp = gvPhotoHW.GetRow(index) as FileAttribute;
                        selectedPhotos.Add(pp);
                    }
                    // browser.Items.Clear();
                    browser = new RasterThumbnailBrowser();

                    RegBrowserEvent();
                    RasterCodecs.Startup();
                    RasterCodecs codecs = new RasterCodecs();
                    RasterImage img = null;
                    RasterImageListItem item = null;
                    // dragThumbs.Clear();                     //拖曳操作选中的照片
                    foreach (FileAttribute p in photos.Where(p => p.IsPic))
                    {
                        try
                        {
                            //img = codecs.ReadStamp(p.FullName, 1);
                            item = p.Thumb;

                            img = p.Image;
                            if (item == null || img == null)
                            {
                                img = GetStampPic(p.FullName);

                                p.Image = img;
                                item = new RasterImageListItem(img, 1, p.FileName);

                                item.Tag = p; //缩略图和数据关联
                                p.Thumb = item;


                            }
                            browser.Items.Add(item);
                            if (selectedPhotos.Contains(p))
                            {
                                dragThumbs.Add(item);
                                item.Selected = true;
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    //没有缩略图就不加载

                    RasterCodecs.Shutdown();
                    //加载缩略图控件
                    browser.Dock = DockStyle.Fill;
                    browser.SelectionMode = RasterImageListSelectionMode.Multi;


                    pPhotoDetail.Controls.Clear();
                    pPhotoDetail.Controls.Add(browser);
                    DisplayMode = true;
                }

                ListFileDrog = selectedPhotos;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                ShowMsg(ex.Message);
            }
        }
        /// <summary>
        /// 显示文件列表
        /// </summary>
        void DisplayPhoto()
        {
            if (!DisplayMode)
            {
                gcPhotoHW.DataSource = ListFileDisplay;
                gcPhotoHW.RefreshDataSource();
            }
            else
            {
                List<FileAttribute> selectedPhotos = new List<FileAttribute>();
                int[] indexes = gvPhotoHW.GetSelectedRows(); //当前选中的照片
                foreach (int index in indexes)
                {
                    FileAttribute pp = gvPhotoHW.GetRow(index) as FileAttribute;
                    selectedPhotos.Add(pp);
                }

                browser = new RasterThumbnailBrowser();

                RegBrowserEvent();
                RasterCodecs.Startup();
                RasterCodecs codecs = new RasterCodecs();
                RasterImage img = null;
                RasterImageListItem item = null;
                // dragThumbs.Clear();                     //拖曳操作选中的照片
                foreach (FileAttribute p in ListFileDisplay.Where(p => p.IsPic))
                {
                    try
                    {
                        //img = codecs.ReadStamp(p.FullName, 1);
                        item = p.Thumb;
                        ///item.
                        img = p.Image;
                        if (item == null || img == null)
                        {
                            img = GetStampPic(p.FullName);

                            p.Image = img;
                            item = new RasterImageListItem(img, 1, p.FileName);


                            item.Tag = p; //缩略图和数据关联
                            p.Thumb = item;


                        }

                        browser.Items.Add(item);
                        if (selectedPhotos.Contains(p))
                        {
                            dragThumbs.Add(item);
                            item.Selected = true;
                        }

                    }
                    catch (Exception ex)
                    {
                    }
                }


                RasterCodecs.Shutdown();
                //加载缩略图控件
                browser.Dock = DockStyle.Fill;
                browser.SelectionMode = RasterImageListSelectionMode.Multi;

                pPhotoDetail.Controls.Clear();
                pPhotoDetail.Controls.Add(browser);
                DisplayMode = true;
            }
        }

        #region 设置缩略图的拖曳操作
        int clickTimes = 1;
        bool IsCtrlDown = false;                                                    //ctrl键是否按下
        bool IsShiftDown = false;                                                   //shift键是否按下
        List<RasterImageListItem> dragThumbs = new List<RasterImageListItem>();
        Point ClickLocation;

        private void RegBrowserEvent()
        {
            browser.MouseDown += new MouseEventHandler(browser_MouseDown);
            browser.MouseMove += new MouseEventHandler(browser_MouseMove);
            browser.MouseUp += new MouseEventHandler(browser_MouseUp);
            browser.KeyDown += new KeyEventHandler(browser_KeyDown);
            browser.KeyUp += new KeyEventHandler(browser_KeyUp);
        }

        void browser_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IsCtrlDown = false;
                IsShiftDown = false;
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }

        void browser_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Modifiers == Keys.Control)
                {
                    IsCtrlDown = true;
                }
                else if (e.Modifiers == Keys.Shift)
                {
                    IsShiftDown = true;
                }
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }

        void browser_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                ClickLocation = new Point(e.X, e.Y);
                RasterImageListItem item = browser.HitTest(e.X, e.Y);
                if (item != null)
                {
                    if (dragThumbs.Contains(item))                  //当前位置缩略图已被选中
                    {
                        foreach (RasterImageListItem tt in dragThumbs)
                        {
                            tt.Selected = true;
                        }
                    }
                    else
                    {
                        if (IsCtrlDown)
                        {
                            dragThumbs.Add(item);
                        }
                        else if (IsShiftDown)
                        {
                            dragThumbs.Clear();
                            RasterImageListItemCollection items = browser.SelectedItems;
                            foreach (RasterImageListItem tt in items)
                            {
                                dragThumbs.Add(tt);
                            }
                        }
                        else
                        {
                            dragThumbs.Clear();
                            dragThumbs.Add(item);
                        }
                    }
                    clickTimes = 2;             //可执行拖曳操作
                }
                else
                {
                    dragThumbs.Clear();
                    clickTimes = 1;             //可执行选择操作
                }
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }
        void browser_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (clickTimes == 2 && e.Button == MouseButtons.Left)  //拖曳
                {
                    Size dragSize = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(ClickLocation.X - dragSize.Width / 2, ClickLocation.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height);
                    if (!rec.Contains(e.X, e.Y))
                    {
                        List<string> pathes = new List<string>();
                        foreach (RasterImageListItem item in dragThumbs)
                        {
                            FileAttribute p = (FileAttribute)item.Tag;
                            pathes.Add(p.FullName);
                        }
                        string[] photoPathes = pathes.ToArray();
                        DataObject data = new DataObject(DataFormats.FileDrop, photoPathes);
                        DoDragDrop(data, DragDropEffects.All);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }

        void browser_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                if (clickTimes == 1)
                {
                    dragThumbs.Clear();
                    RasterImageListItemCollection items = browser.SelectedItems;
                    foreach (RasterImageListItem item in items)
                    {
                        dragThumbs.Add(item);
                    }
                }
                //string name = "";
                //foreach (RasterImageListItem item in dragThumbs)
                //{
                //    name += "|" + item.Text;
                //}
                //MessageBox.Show(dragThumbs.Count.ToString()+name);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 读图
        /// </summary>
        /// <param name="picPath"></param>
        /// <returns></returns>
        public RasterImage GetStampPic(string picPath)
        {
            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
            RasterImage image1 = null;
            CodecsThumbnailOptions options = CodecsThumbnailOptions.Default;
            options.LoadStamp = true;
            options.Resample = true;

            //options.Width = rasterP1.Width;
            //options.Height = rasterP1.Height;
            options.MaintainAspectRatio = false;
            try
            {
                image1 = codecs.ReadThumbnail(picPath, options, 1);
            }
            catch
            {
                options.LoadStamp = false;
                image1 = codecs.ReadThumbnail(picPath, options, 1);

            }
            codecs.Dispose();
            RasterCodecs.Shutdown();

            return image1;
        }
        GridHitInfo hitInfo = null;
        private void gvPhotoHW_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left && hitInfo != null && (hitInfo.HitTest == GridHitTest.RowCell || hitInfo.HitTest == GridHitTest.Row || hitInfo.HitTest == GridHitTest.RowEdge))
                {
                    Size size = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(hitInfo.HitPoint.X - size.Width / 2, hitInfo.HitPoint.Y - size.Height / 2, size.Width, size.Height);
                    if (!rec.Contains(e.X, e.Y) && hitInfo.HitTest != GridHitTest.RowIndicator)
                    {
                        int[] indexes = gvPhotoHW.GetSelectedRows();
                        if (indexes == null || indexes.Count() == 0)
                            return;
                        List<string> pathes = new List<string>();
                        foreach (int index in indexes)
                        {
                            pathes.Add(gvPhotoHW.GetRowCellValue(index, "FullName").ToString());
                        }
                        //DataObject data = new DataObject("photo", pathes);
                        string[] photoPathes = pathes.ToArray();
                        DataObject data2 = new DataObject(DataFormats.FileDrop, photoPathes);
                        DoDragDrop(data2, DragDropEffects.All);
                        hitInfo = null;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }

        private void gvPhotoHW_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                hitInfo = gvPhotoHW.CalcHitInfo(e.Location);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }
        private void tsExpand_Click(object sender, EventArgs e)
        {
            if (gridViewListView.GroupCount > 0)
            {

                string txt = tsExpand.Text;
                if (txt.Contains("展开"))
                {
                    gridViewListView.ExpandAllGroups();
                    tsExpand.Text = "合拢&V";
                }
                else if (txt.Contains("合拢"))
                {
                    gridViewListView.CollapseAllGroups();
                    tsExpand.Text = "展开&V";
                }
            }
        }

        private void browser1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control)
            {
                IsCtrlDown = true;
            }
            if (e.KeyCode == Keys.S)
            {
                SavePickupDir();
            }

        }
        /// <summary>
        /// 保存已经整理好的文件
        /// 
        /// </summary>
        void SavePickupDir()
        {
            string currPath = CurrSelectPath;//设定改文件夹下的照片为已经整理号标志OK
            if (MessageBox.Show("是否保存文件夹" + currPath + "下的文件", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
            {
                currPath = DisposeTotalPath + currPath.Split(':')[1];
                try
                {
                    //先判断文件夹是否已存在于商户文件夹中
                    string currFolder = currPath.Substring(currPath.LastIndexOf("\\") + 1).Trim();

                    if (currPath.EndsWith("OK"))
                    {
                        MessageBox.Show("该操作不能用于商户文件夹！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    DataRowView shop = (DataRowView)lbShop.SelectedItem;
                    if (shop == null)
                    {
                        MessageBox.Show("请先在左边列表中选中商户！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    //弹出对话框，选择商户
                    FrmSetShop frm = new FrmSetShop();
                    frm.frm = this;
                    frm.ShopDt = AllShop;
                    frm.ShopId = Convert.ToInt32(shop["ShopId"]);
                    if (DialogResult.OK == frm.ShowDialog())
                    {
                        string shopName = SelectedShopName + "OK";                              //结尾加上OK是为了 区分真正的已完成整理的文件夹
                        lbShop.SelectedValue = SelectedShopId;
                        //1 判断商户文件夹是否存在，如果不存在，就创建

                        string[] directories = Directory.GetDirectories(DisposeTotalPath);
                        string shopPath = RootPath + @"\" + CurrUserName + @"\" + shopName;
                        if (!Directory.Exists(shopPath))
                        {

                            Directory.CreateDirectory(shopPath);

                        }
                        //2 将指定的文件夹剪切到商户文件夹中

                        string[] subDirectories = Directory.GetDirectories(shopPath);
                        foreach (string subDirectory in subDirectories)
                        {
                            if (subDirectory.Substring(subDirectory.LastIndexOf("\\") + 1) == currFolder)
                            {
                                MessageBox.Show("目标文件夹中已存在相同名字的文件夹，请先重命名！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }
                        }
                      
                        DirectoryInfo dinfo = new DirectoryInfo(currPath);
                        dinfo.Attributes = FileAttributes.Normal;                   //去掉可能的只读属性
                        
                        string toalDir = shopPath + "\\" + currFolder;
                        //if (!Directory.Exists(toalDir))
                        //{
                        //    Directory.CreateDirectory(toalDir);
                        //}
                        
                        bool bo = MoveFile(currPath, toalDir, 2);

                        if (!bo)
                        {
                            //Directory.Move(currPath, toalDir);//换个方式重新尝试移动

                            string outErrMsg = string.Empty;

                            if (!MoveDirectory(currPath, toalDir, out outErrMsg))
                            {
                                //删除OK目录
                                FileBLL.DeleteDirectory(toalDir);//将这个商户下面的所有产品都删除掉,以便重新开单
                                if (Directory.GetDirectories(shopPath).Length <= 0)//ok目录下如果没有文件夹了，则册除该OK目录
                                {
                                    FileBLL.DeleteDirectory(shopPath);
                                }
                                ShowMsg(outErrMsg);

                                return;
                            }

                            //如果开单成功则删除原来的文件夹
                            FileBLL.DeleteDirectory(currPath);
                        }





                        int lastIndex = currPath.LastIndexOf('\\');
                        if (lastIndex > 0)
                        {
                            string Path = currPath.Substring(0, lastIndex);
                            Path = Path.Replace(DisposeTotalPath, "V:");
                            TreeNode node = browser1.SelectPath(Path, true);
                            //node.Collapse(true);
                            //node.Collapse(false);
                            browser1.Show();
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShowMsg(ex.Message + "(请查看移动的文件夹是否是打开的)");
                }
            }
        }
        /// <summary>
        /// 移动目录,如果目标处没有此目录，则创建
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dst"></param>
        /// <returns></returns>
        public static bool MoveDirectory(string src, string dst, out string errMsg)
        {
            errMsg = "";
            //string FolderName = src.Substring(src.LastIndexOf("\\") + 1);
            //dst += "\\" + FolderName;

            try
            {
                if (!Directory.Exists(dst))
                {
                    Directory.CreateDirectory(dst);
                }

                foreach (var fi in Directory.GetFiles(src))
                {
                    //MoveFile(fi, dst + "\\" + fi.Substring(fi.LastIndexOf("\\") + 1), 2);
                    //File.Copy(fi, dst + "\\" + fi.Substring(fi.LastIndexOf("\\") + 1), true);

                    FileInfo fiTemp = new FileInfo(fi);
                    //判断文件属性是否只读?是则修改为一般属性再删除
                    if (fiTemp.Attributes.ToString().IndexOf("ReadOnly") != -1)
                    {
                        fiTemp.Attributes = FileAttributes.Normal;
                    }


                    if (FileBLL.CopyFileA(fi, dst + "\\" + fi.Substring(fi.LastIndexOf("\\") + 1), 0) == 0)
                    {
                        errMsg = "在移动文件时出错\n" + fi;
                        return false;
                    }
                }
                foreach (var di in Directory.GetDirectories(src))
                {
                    string FolderName = dst+"\\"+di.Substring(di.LastIndexOf("\\") + 1);
                    if (!MoveDirectory(di, FolderName, out errMsg))//如果出错了就中断
                        return false;
                }

            }
            catch (Exception ex)
            {
                errMsg = "在移动文件时出错：\n" + ex.Message;
                return false;
            }
            return true;
        }
        #region 根据商户的助记码变化筛选商户
        //根据商户的助记码变化筛选商户
        private void txtShopZJM_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string zjcode = txtShopZJM.Text;
                DataTable filterDt = AllShop.Clone();
                DataRow[] rows = AllShop.Select("ZJCode like '%" + zjcode + "%'");
                foreach (DataRow r in rows)
                {
                    DataRow nr = filterDt.NewRow();
                    nr.ItemArray = r.ItemArray;
                    filterDt.Rows.Add(nr);
                }
                DataRow[] rows2 = AllShop.Select("ShopName like '%" + zjcode + "%'");
                foreach (DataRow r in rows2)
                {
                    DataRow nr = filterDt.NewRow();
                    nr.ItemArray = r.ItemArray;
                    filterDt.Rows.Add(nr);
                }
                BindShop(filterDt);
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }
        #endregion

        private void FrmDisposeMain_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.Modifiers == Keys.Control)
            {
                IsCtrlDown = true;

            }
            if (IsCtrlDown)
            {
                if (e.KeyCode == Keys.S)
                {
                    SavePickupDir();
                }
                if (e.KeyCode == Keys.L)
                {
                    buttonShowPic_Click(null, null);
                }
            }

        }
        /// <summary>
        /// 检查是否有理好件的文件夹存在
        /// </summary>
        /// <returns></returns>
        private bool CheckIsOkExist(string inPath)
        {
            try
            {
                bool isExist = false;
                string[] subDirectories = Directory.GetDirectories(DisposeTotalPath);
                foreach (string subDirectory in subDirectories)
                {
                    if (subDirectory.EndsWith("OK"))
                    {
                        isExist = true;
                        break;
                    }
                }
                return isExist;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 重命名文件夹时，防止文件夹重名的操作
        /// </summary>
        /// <param name="folders"></param>
        /// <param name="x"></param>
        /// <param name="folderName"></param>
        /// <returns></returns>
        private string GetNewFolderName(List<string> folders, int x, string folderName)
        {
            string newFolderName = folderName;
            if (x > 1)
            {
                newFolderName = folderName + " (" + x.ToString() + ")";
            }
            foreach (string f in folders)
            {
                if (f.Substring(f.LastIndexOf("\\") + 1) == newFolderName)
                {
                    x++;
                    newFolderName = GetNewFolderName(folders, x, folderName);
                    break;
                }
            }
            return newFolderName;
        }
        /// <summary>
        /// 移动到等带开单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsSave_Click(object sender, EventArgs e)
        {
            try
            {
                string pickupOK = StartOrderTotalPath.Substring(0, StartOrderTotalPath.LastIndexOf("\\")) + @"\理件\" + CurrUserName;//
                if (!CheckIsOkExist(pickupOK))
                {
                    ShowMsg(CurrUserName + "已经保存完毕。");
                    return;
                }
                Cursor = Cursors.WaitCursor;
                FrmSetUser frm = new FrmSetUser();
                frm.UserDt = AllUser;
                frm.UserId = SelectedUserId;
                frm.frm = this;
                if (DialogResult.OK == frm.ShowDialog())
                {
                    //lblStartOrder.Text = SelectedUserName;
                    //lblStartOrder.Tag = SelectedUserId;
                    //string startOrderUserName = lblStartOrder.Text.Trim();              //开单员名字
                    string startOrderUserPath = StartOrderTotalPath + "\\" + SelectedUserName;        //开单员的开单路径
                    if (!Directory.Exists(startOrderUserPath))                          //如果该开单员的开单路径还不存在，就新建
                    {
                        Directory.CreateDirectory(startOrderUserPath);
                    }
                    string[] subDirectories = Directory.GetDirectories(pickupOK);
                    string shopOkName = "";               //商户+OK名
                    string shopName = "";               //商户名
                    string shopPath = "";               //商户开单路径
                    foreach (string subDirectory in subDirectories)
                    {
                        if (subDirectory.EndsWith("OK"))                //OK结束，表示是已理件文件夹
                        {
                            shopOkName = subDirectory.Substring(subDirectory.LastIndexOf("\\") + 1);
                            shopName = shopOkName.Substring(0, shopOkName.LastIndexOf("OK"));       //商户名
                            shopPath = startOrderUserPath + "\\" + shopName;
                            if (!Directory.Exists(shopPath))                    //商户不存在，就创建
                            {
                                Directory.CreateDirectory(shopPath);
                            }
                            if (!Directory.Exists(shopPath + "\\已开单"))       //"已开单"不存在，就创建
                            {
                                Directory.CreateDirectory(shopPath + "\\已开单");
                            }
                            string[] ssubDirectories = Directory.GetDirectories(subDirectory);
                            string[] oldCtmPathes = Directory.GetDirectories(shopPath);     //原有的客户
                            List<string> oldCtmNames = new List<string>();
                            foreach (string cp in oldCtmPathes)
                            {
                                oldCtmNames.Add(cp.Substring(cp.LastIndexOf("\\") + 1));
                            }

                            int sameName = 0;                                   //1重命名后再移动 2不重命名，放弃移动
                            string currentCtmName = "";
                            foreach (string ssubDirectory in ssubDirectories)   //将所有整理好的客户文件夹剪切到目标商户下
                            {
                                //r = MoveFile(ssubDirectory, shopPath + "\\" + ssubDirectory.Substring(ssubDirectory.LastIndexOf("\\") + 1), 1 | 2);
                                currentCtmName = ssubDirectory.Substring(ssubDirectory.LastIndexOf("\\") + 1).Trim();
                                if (oldCtmNames.Contains(currentCtmName))
                                {
                                    if (sameName == 0)
                                    {
                                        if (DialogResult.Yes == MessageBox.Show("等待开单中已存同名的客人名，要自动重命名再移动吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                                        {
                                            sameName = 1;
                                        }
                                        else
                                        {
                                            sameName = 2;
                                        }
                                    }
                                    if (sameName == 1)
                                    {
                                        currentCtmName = GetNewFolderName(oldCtmPathes.ToList(), 1, currentCtmName);
                                    }
                                    else if (sameName == 2)
                                    {
                                        continue;
                                    }
                                }
                                currentCtmName = currentCtmName.Trim();
                                //Directory.Move(ssubDirectory, shopPath + "\\" + currentCtmName);
                                bool ss=MoveFile(ssubDirectory, shopPath + "\\" + currentCtmName, 2);
                            }
                            //删除原商户OK目录
                            Directory.Delete(subDirectory);
                        }
                    }
                    Cursor = Cursors.Default;
                    ShowMsg("理件文件夹保存成功！");
                }
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                ShowMsg(ex.Message);
            }
        }

        private void tsSetDisposePath_Click(object sender, EventArgs e)
        {
            try
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    Cursor = Cursors.WaitCursor;
                    string path = folderBrowserDialog1.SelectedPath;
                    bll.UpdateUserDisposePath(UserId, path);
                    DisposeTotalPath = path;
                    //重新加载理件树
                    // tvExplorer.Nodes.Clear();
                    lblTS.Visible = false;
                    //  AddTree();
                    Cursor = Cursors.Default;
                    try
                    {


                        if (!CreatNetConn("V:", path))
                        {
                            ShowMsg("请先删除现有名称为V的网络映射");
                        }
                        else
                        {
                            ShowMsg("设置成功");

                        }
                    }
                    catch (Exception exception)
                    {


                    }

                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                ShowMsg(ex.Message);
            }
        }

        private void tsRefreshPath_Click(object sender, EventArgs e)
        {
            browser1.Refresh();
        }

        int intGFloor = Properties.Settings.Default.IntFloorNum;

        private string[,] TempTable = null;
        private void toolStripButtonDetail_Click(object sender, EventArgs e)
        {
            //this.Cursor = Cursors.WaitCursor;

            gridViewListView.Columns.Clear();
            gridViewListView.GroupSummary.Clear();

            ListSizeNum = new List<SizeNum>();


            try
            {
                DisplayTables(true);

                #region

                //if (intFloor == 0)
                //{
                //    intFloor = 2;
                //}

                //int intColumnCount = intFloor + 3;//总的列数
                //DataTable dataTable = new DataTable("Data");


                ////GetDirInfo(CurrSelectPath);
                ////SetPhotoGroup();
                //List<SizeNum> listSize = GetInfo(CurrSelectPath, intFloor);
                //for (int i = 0; i < intFloor; i++)
                //{
                //    GridColumn gridColumn = new DevExpress.XtraGrid.Columns.GridColumn();

                //    gridColumn.Name = "gridColumn" + i;
                //    gridColumn.Caption = "目录" + (i + 1);
                //    gridColumn.Visible = true;
                //    gridColumn.Width = 50;
                //    gridColumn.FieldName = "Column" + (i + 1);
                //    gridColumn.VisibleIndex = i;
                //    gridColumn.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                //    dataTable.Columns.Add("Column" + (i + 1));
                //    gridViewListView.Columns.Add(gridColumn);

                //}
                //GridColumn SizeIn = new DevExpress.XtraGrid.Columns.GridColumn();
                //SizeIn.Name = "SizeIn";
                //SizeIn.Caption = "尺寸(in)";
                //SizeIn.Width = 50;
                //SizeIn.FieldName = "SizeIn";
                //SizeIn.VisibleIndex = intFloor + 1;
                //SizeIn.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                //gridViewListView.Columns.Add(SizeIn);

                //dataTable.Columns.Add("SizeIn", typeof(string));

                //GridColumn SizeCm = new DevExpress.XtraGrid.Columns.GridColumn();
                //SizeCm.Name = "SizeCm";
                //SizeCm.Caption = "尺寸(cm)";
                //SizeCm.Width = 50;
                //SizeCm.FieldName = "SizeCm";
                //SizeCm.VisibleIndex = intFloor + 2;
                //SizeCm.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                //gridViewListView.Columns.Add(SizeCm);

                ////gridViewListView.Columns.Add(new GridColumn() { Name = "SizeCm", Caption = "尺寸(cm)", Visible = true, Width = 50, FieldName = "SizeCm", VisibleIndex = intFloor + 2 });
                //dataTable.Columns.Add("SizeCm", typeof(string));

                //GridColumn Num = new DevExpress.XtraGrid.Columns.GridColumn();
                //Num.Name = "Num";
                //Num.Caption = "数量";
                //Num.Width = 50;
                //Num.FieldName = "Num";
                //Num.VisibleIndex = intFloor + 3;
                //Num.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                //gridViewListView.Columns.Add(Num);
                ////gridViewListView.Columns.Add(new GridColumn() { Name = "Num", Caption = "数量", Visible = true, Width = 50, FieldName = "Num", VisibleIndex = intFloor + 3 });
                //dataTable.Columns.Add("Num", typeof(string));
                ////DevExpress.XtraGrid.Columns.GridColumn colId = gridViewListView.Columns.Add();
                //GridGroupSummaryItem item = new GridGroupSummaryItem();
                //item.FieldName = "Num";
                //item.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                //item.DisplayFormat = "数量={0}";
                //gridViewListView.GroupSummary.Add(item);


                //int rowNum = 0;

                //TempTable = new string[listSize.Count, intColumnCount];
                //foreach (SizeNum sizeNum in listSize)
                //{
                //    //gridViewListView.AddNewRow();
                //    DataRow row = dataTable.NewRow();
                //    for (int j = 0; j < intColumnCount; j++)
                //    {
                //        if (j < intFloor)
                //        {
                //            TempTable[rowNum, j] = sizeNum.DirKey.Split('\\')[j];
                //            //GetUnitCellsInfo(rowNum, j, sizeNum.DirKey.Split('\\')[j], TempTable);
                //            row[j] = sizeNum.DirKey.Split('\\')[j];
                //            //gridViewListView.SetRowCellValue(rowNum, gridViewListView.Columns[j],
                //            //                                 sizeNum.DirKey.Split('\\')[j].ToString());
                //        }
                //    }
                //    TempTable[rowNum, intFloor] = sizeNum.SizeCm;

                //    //GetUnitCellsInfo(rowNum, intFloor, sizeNum.SizeCm, TempTable);
                //    TempTable[rowNum, intFloor + 1] = sizeNum.SizeIn;
                //    //GetUnitCellsInfo(rowNum, intFloor + 1, sizeNum.SizeIn, TempTable);
                //    TempTable[rowNum, intFloor + 2] = sizeNum.Num.ToString();
                //    // GetUnitCellsInfo(rowNum, intFloor + 2, sizeNum.Num.ToString(), TempTable);
                //    //gridViewListView.SetRowCellValue(rowNum, gridViewListView.Columns["SizeIn"],
                //    //                                       sizeNum.SizeCm);
                //    //gridViewListView.SetRowCellValue(rowNum, gridViewListView.Columns["SizeCm"],
                //    //                                         sizeNum.SizeIn);
                //    //gridViewListView.SetRowCellValue(rowNum, gridViewListView.Columns["Num"],
                //    //                                         sizeNum.Num);
                //    row["SizeCm"] = sizeNum.SizeCm;
                //    row["SizeIn"] = sizeNum.SizeIn;
                //    row["Num"] = sizeNum.Num;
                //    dataTable.Rows.Add(row);
                //    rowNum++;
                //}
                //gridControlView.DataSource = dataTable;
                //gridControlView.RefreshDataSource();
                //gridViewListView.set

                #endregion

            }
            catch (Exception ex)
            {

            }
            finally
            {
                //this.Cursor = Cursors.Default;
            }
        }
        //thre

        FrmProcess frmPro = null;
        private void OpenProgress()
        {
            try
            {
                frmPro = new FrmProcess();
                frmPro.ShowDialog();
            }
            catch { }
        }
        private void CloseProgress()
        {
            if (frmPro != null)
            {
                frmPro.Close();
            }
        }
        delegate void CloseProgressFrm();
        void DisplayTables(bool isAutoAnlyse)
        {
            //System.Threading.Thread th = new Thread(OpenProgress);
            //th.IsBackground = true;
            try
            {


                //th.Start();
                this.Cursor = Cursors.WaitCursor;
                int intFloor = Properties.Settings.Default.IntFloorNum;
                gridViewListView.Columns.Clear();
                gridViewListView.GroupSummary.Clear();

                //gridViewListView.RowCellClick+=new RowCellClickEventHandler(gridViewListView_RowCellClick);

                listUnit = new List<UnitCell>();
                if (intFloor == 0)
                {
                    intFloor = 2;
                }
                List<SizeNum> listSize = GetInfo(CurrSelectPath, intFloor, isAutoAnlyse);
                #region//创建view和table的结构
                int intColumnCount = intFloor + 3; //总的列数
                DataTable dataTable = new DataTable("Data");


                //GetDirInfo(CurrSelectPath);
                //SetPhotoGroup();

                foreach (var kvp in listSize.GroupBy(p => p.DirKey))
                {

                    List<SizeNum> listSizes = listSize.Where(p => p.DirKey == kvp.Key).ToList();
                    if (listSizes.Count > 1)
                    {
                        SizeNum MinTemp =
                            listSize.Where(p => p.DirKey == kvp.Key).ToList().OrderBy(p => p.Num).FirstOrDefault();
                        SizeNum MaxTemp =
                            listSize.Where(p => p.DirKey == kvp.Key).ToList().OrderByDescending(p => p.Num).
                                FirstOrDefault();
                        if (MinTemp.Num == MaxTemp.Num)
                        {

                        }
                        else if (MaxTemp.Num == 1)
                        {
                        }
                        else
                        {
                            MinTemp.FlagRed = 1;
                        }

                    }
                    var sn = listSizes.FindAll(p => p.ListPhoto.Find(pt => pt.DPI < 72) != null);
                    foreach (var ss in sn)
                    {
                        if (ss != null)
                        {
                            ss.FlagRed = 1;
                        }
                    }

                    //foreach (SizeNum sn in listSizes)
                    //{ }
                }
                //listSize.GroupBy(p => p.DirKey.Replace("\\<空>", "")).ToList();
                RepositoryItemHyperLinkEdit repositoryItemHyperLinkEditDir;
                for (int i = 0; i < intFloor; i++)
                {
                    GridColumn gridColumn = new DevExpress.XtraGrid.Columns.GridColumn();

                    gridColumn.Name = "gridColumn" + i;
                    gridColumn.Caption = "目录" + (i + 1);
                    gridColumn.Visible = true;
                    gridColumn.Width = 50;
                    gridColumn.FieldName = "Column" + (i + 1);
                    gridColumn.VisibleIndex = i;
                    gridColumn.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                    gridColumn.OptionsColumn.ReadOnly = true;
                    gridColumn.OptionsColumn.AllowEdit = false;
                    gridColumn.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                    gridViewListView.Columns.Add(gridColumn);
                    repositoryItemHyperLinkEditDir = new RepositoryItemHyperLinkEdit();

                    gridColumn.ColumnEdit = repositoryItemHyperLinkEditDir;
                    dataTable.Columns.Add("Column" + (i + 1));


                }
                GridColumn SizeIn = new DevExpress.XtraGrid.Columns.GridColumn();
                SizeIn.Name = "SizeIn";
                SizeIn.Caption = "尺寸(in)";
                SizeIn.Width = 50;
                SizeIn.FieldName = "SizeIn";
                SizeIn.VisibleIndex = intFloor + 1;
                SizeIn.OptionsColumn.ReadOnly = true;
                SizeIn.OptionsColumn.AllowEdit = false;
                SizeIn.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                SizeIn.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                gridViewListView.Columns.Add(SizeIn);

                dataTable.Columns.Add("SizeIn", typeof(string));

                GridColumn SizeCm = new DevExpress.XtraGrid.Columns.GridColumn();
                SizeCm.Name = "SizeCm";
                SizeCm.Caption = "尺寸(cm)";
                SizeCm.Width = 50;
                SizeCm.FieldName = "SizeCm";
                SizeCm.VisibleIndex = intFloor + 2;
                SizeCm.OptionsColumn.ReadOnly = true;
                SizeCm.OptionsColumn.AllowEdit = false;
                SizeCm.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                SizeCm.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
                gridViewListView.Columns.Add(SizeCm);

                //gridViewListView.Columns.Add(new GridColumn() { Name = "SizeCm", Caption = "尺寸(cm)", Visible = true, Width = 50, FieldName = "SizeCm", VisibleIndex = intFloor + 2 });
                dataTable.Columns.Add("SizeCm", typeof(string));

                GridColumn Num = new DevExpress.XtraGrid.Columns.GridColumn();
                Num.Name = "Num";
                Num.Caption = "数量";
                Num.Width = 50;
                Num.FieldName = "Num";
                Num.VisibleIndex = intFloor + 3;
                Num.OptionsColumn.ReadOnly = true;
                Num.OptionsColumn.AllowEdit = true;
                Num.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                Num.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                gridViewListView.Columns.Add(Num);
                //gridViewListView.Columns.Add(new GridColumn() { Name = "Num", Caption = "数量", Visible = true, Width = 50, FieldName = "Num", VisibleIndex = intFloor + 3 });

                dataTable.Columns.Add("Num", typeof(string));

                GridColumn Link = new DevExpress.XtraGrid.Columns.GridColumn();
                Link.Name = "Link";
                Link.Caption = "打开";
                Link.Width = 50;
                Link.FieldName = "Link";
                Link.VisibleIndex = intFloor + 4;
                Link.OptionsColumn.ReadOnly = true;
                Link.OptionsColumn.AllowEdit = false;
                Link.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                Link.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                RepositoryItemHyperLinkEdit repositoryItemHyperLinkEdit1 = new RepositoryItemHyperLinkEdit();

                Link.ColumnEdit = repositoryItemHyperLinkEdit1;
                gridViewListView.Columns.Add(Link);

                dataTable.Columns.Add("Link", typeof(string));
                dataTable.Columns.Add("Path", typeof(string));
                dataTable.Columns.Add("FlagRed", typeof(int));
                dataTable.Columns.Add("DirKey", typeof(string));

                //DevExpress.XtraGrid.Columns.GridColumn colId = gridViewListView.Columns.Add();
                GridGroupSummaryItem item = new GridGroupSummaryItem();//添加分组数据
                item.FieldName = "Num";
                item.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                item.DisplayFormat = "数量={0}";
                gridViewListView.GroupSummary.Add(item);

                #endregion
                int rowNum = 0;
                int NumCount = 0;
                TempTable = new string[listSize.Count, intColumnCount];
                foreach (SizeNum sizeNum in listSize)
                {
                    //gridViewListView.AddNewRow();
                    DataRow row = dataTable.NewRow();
                    for (int j = 0; j < intColumnCount; j++)
                    {
                        if (j < intFloor)
                        {

                            row[j] = sizeNum.DirKey.Split('\\')[j];

                        }
                    }

                    row["SizeCm"] = sizeNum.SizeCm;
                    row["SizeIn"] = sizeNum.SizeIn;
                    row["Num"] = sizeNum.Num;
                    if (sizeNum.Num == 1)
                    {

                        string photoFullPath = sizeNum.ListPhoto.FirstOrDefault().FullPath;
                        row["Link"] = photoFullPath.Substring(photoFullPath.LastIndexOf("\\") + 1);
                        row["Path"] = photoFullPath.Substring(0, photoFullPath.LastIndexOf('\\'));

                    }
                    else
                    {
                        string photoFullPath = sizeNum.ListPhoto.FirstOrDefault().FullPath;
                        row["Path"] = photoFullPath.Substring(0, photoFullPath.LastIndexOf('\\'));
                        row["Link"] = "...";
                    }
                    row["FlagRed"] = sizeNum.FlagRed;
                    row["DirKey"] = sizeNum.DirKey;
                    dataTable.Rows.Add(row);
                    rowNum++;
                    NumCount += sizeNum.Num;
                }
                gridControlView.DataSource = dataTable;
                gridControlView.RefreshDataSource();
                toolStripLabelCurrNum.Text = "数量:" + NumCount;

                //try
                //{
                //    th.Abort();
                //}
                //catch (ThreadAbortException exxx)
                //{
                //    Thread.ResetAbort();
                //}
                //th.Join();

            }
            catch (Exception ex)
            {
                Thread.ResetAbort();
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                this.Invoke(new CloseProgressFrm(CloseProgress));
            }
        }

        List<UnitCell> listUnit = new List<UnitCell>();
        /// <summary>
        /// 获得合并格子的信息
        /// </summary>
        /// <param name="inX"></param>
        /// <param name="inY"></param>
        /// <param name="inValue"></param>
        /// <param name="inArr"></param>
        public void GetUnitCellsInfo(int inX, int inY, string inValue, string[,] inArr)
        {
            if (inX - 1 < 0)//第一行
            {
                //listUnit.Add(new UnitCell() { StartPosition = new Point(0, inY), CellValue = inValue, EndPosition = new Point(0, inY) });
            }
            else
            {
                if (inY - 1 < 0)//第一列
                {
                    if ((inArr[inX - 1, inY]).ToString().Equals((inArr[inX, inY])))
                    {

                        //if(inX-1>0)
                        //{
                        //    listUnit.Add(new UnitCell()
                        //                     {
                        //                         StartPosition = new Point(inX - 1, inY),
                        //                         CellValue = inValue,
                        //                         EndPosition = new Point(inX, inY)
                        //                     });
                        //}
                        //else
                        //{

                        //}
                        UnitCell unitCell = listUnit.FirstOrDefault(p => p.EndPosition.X == inX - 1 && p.EndPosition.Y == inY);
                        if (unitCell == null)
                        {
                            listUnit.Add(new UnitCell()
                                             {
                                                 StartPosition = new Point(inX - 1, inY),
                                                 CellValue = inValue,
                                                 EndPosition = new Point(inX, inY)
                                             });
                        }
                        else
                        {
                            unitCell.EndPosition = new Point(inX, inY);
                        }


                    }

                }
                else
                {
                    //if ((inArr[inX - 1, inY]).ToString().Equals((inArr[inX, inY])) && (inArr[inX, inY]).Equals(inArr[inX, inY - 1]))
                    //if (CheckCells(inX, inY, inArr))
                    //{

                    //    listUnit.Add(new UnitCell() { StartPosition = new Point(inX - 1, inY), CellValue = inValue, EndPosition = new Point(inX - 1, inY)});

                    //}
                    if (CheckCells(inX, inY, inArr))
                    {
                        UnitCell unitCell =
                            listUnit.FirstOrDefault(p => p.EndPosition.X == inX && p.EndPosition.Y == inY);
                        if (unitCell == null)
                        {
                            listUnit.Add(new UnitCell()
                                             {
                                                 StartPosition = new Point(inX - 1, inY),
                                                 CellValue = inValue,
                                                 EndPosition = new Point(inX, inY)
                                             });
                        }
                        else
                        {
                            unitCell.EndPosition = new Point(inX, inY);
                        }
                    }

                }
            }
        }

        private bool CheckCells(int inX, int inY, string[,] inArr)
        {
            bool rtnValue = true;

            if ((inX - 1) < 0 || (inY - 1) < 0)
            {
                return false;
            }
            if (inArr[inX, inY].Equals(inArr[inX - 1, inY]))
            {
                if ((inX - 1) == 0 || (inY - 1) == 0)
                {
                    rtnValue = true;
                }
                else
                {
                    return CheckCells(inX - 1, inY - 1, inArr);
                }

            }
            else
            {
                rtnValue = false;
            }
            return rtnValue;


        }

        private int intMaxLength = 0;
        /// <summary>
        /// 获取所有文件
        /// </summary>
        /// <param name="inPath">路径</param>
        /// <param name="inList">存储容器</param>
        public void GetAllPicByDir(string inPath, List<string> inList)
        {

            string picTag = ".JPEG.JPG.TIF.BMP.TIFF.TXT";
            DirectoryInfo rootDir = new DirectoryInfo(inPath);
            if (rootDir.Exists)
            {
                FileInfo[] fileList = rootDir.GetFiles();
                foreach (FileInfo info in fileList)
                {

                    if (picTag.Contains(info.Extension.ToUpper()))
                    {
                        inList.Add(info.FullName);
                        int currLength = (info.FullName.Split('\\')).Length;
                        if (intMaxLength < currLength)
                        {
                            intMaxLength = currLength;
                        }
                    }

                }
                DirectoryInfo[] listDir = rootDir.GetDirectories();
                foreach (DirectoryInfo dir in listDir)
                {
                    GetAllPicByDir(dir.FullName, inList);
                }
            }

        }

        private List<SizeNum> ListSizeNum = new List<SizeNum>();//缓存信息
        private bool ForcRrefresh = false;
        /// <summary>
        /// 获取目录结构信息
        /// </summary>
        /// <param name="inDir">点击目录</param>
        /// <param name="intFloor">显示层数</param>
        /// <param name="isAutoAnlyse">是否自动分析新路径</param>
        /// <returns></returns>
        private List<SizeNum> GetInfo(string inDir, int intFloor, bool isAutoAnlyse)
        {
            List<string> FileList = new List<string>();
            //if (!isAutoAnlyse)
            //{
            //   return new List<SizeNum>();
            //}
            int pointFloor = inDir.Split('\\').Count();
            GetAllPicByDir(inDir, FileList);
            //int intFloor = Properties.Settings.Default.IntFloorNum;//层
            if (isAutoAnlyse && ListSizeNum != null && ListSizeNum.Count > 1000)
            {
                ListSizeNum = new List<SizeNum>();//清空缓存
            }
            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();

            List<SizeNum> SizeKeyNum = new List<SizeNum>();
            foreach (string fileFullPath in FileList)
            {

                SizeNum sizeNum = new SizeNum();

                sizeNum = new SizeNum();
                sizeNum.Num = 1;
                string[] arrDir = fileFullPath.Substring(inDir.Length + 1).Split('\\');
                int currDirLength = arrDir.Count() - 1;
                string oneStr = "";
                string currDir = "";

                if (currDirLength >= intFloor)
                {
                    #region //显示目录够长的清况

                    for (int i = 0; i < intFloor; i++)
                    {
                        //oneStr = arrDir[i] + "|";//重新组合照片内容
                        currDir += arrDir[i] + "\\"; //重新组合目录
                    }
                    currDir = currDir.Trim('\\');


                    SizeNum sn =
                        ListSizeNum.Where(
                            p =>
                            p.ListPhoto.Where(pt => pt.FullPath.Equals(fileFullPath)).Count() > 0 && p.DirKey.Equals(currDir))
                            .FirstOrDefault();
                    sizeNum.DirKey = currDir;
                    if (sn == null)//缓冲Key中没有读取实际文件
                    {
                        if (!isAutoAnlyse)
                        {
                            continue;
                        }

                        //取得缓存照片信息不用重新读取照片

                        if (!fileFullPath.ToUpper().EndsWith("TXT"))
                        {
                            //找到是否读取过照片
                            SizeNum sizePhotoTemp = ListSizeNum.FirstOrDefault(
                           p =>
                           p.ListPhoto.Where(pt => pt.FullPath.Equals(fileFullPath)).Count() > 0);

                            PhotoInfomation photoInfomation = new PhotoInfomation();

                            if (sizePhotoTemp == null)
                            {
                                CodecsImageInfo img = null;
                                try
                                {
                                    img = codecs.GetInformation(fileFullPath, true);
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show(DateTime.Now + " 发现损坏文件：" + fileFullPath + Environment.NewLine,
                                                    "提示",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Information);

                                    continue;

                                }
                                float Width = (float)img.Width / img.XResolution;
                                float Height = (float)img.Height / img.YResolution;
                                string SizeCM = "";
                                string SizeInch = "";
                                if (Height > Width)
                                {
                                    SizeCM = string.Format("{0:0.##}", Height * 2.54) + "X" +
                                             string.Format("{0:0.##}", Width * 2.54) + "cm";
                                    SizeInch = string.Format("{0:0.##}", Height) + "X" +
                                               string.Format("{0:0.##}", Width) + "in";
                                }
                                else
                                {
                                    SizeCM = string.Format("{0:0.##}", Width * 2.54) + "X" +
                                             string.Format("{0:0.##}", Height * 2.54) + "cm";
                                    SizeInch = string.Format("{0:0.##}", Width) + "X" +
                                               string.Format("{0:0.##}", Height) + "in";
                                }
                                sizeNum.SizeIn = SizeInch;
                                sizeNum.SizeCm = SizeCM;
                                sizeNum.FlagRed = 0;

                                photoInfomation.Width = Width;
                                photoInfomation.Height = Height;
                                photoInfomation.PhotoName = img.Name;
                                photoInfomation.FullPath = fileFullPath;
                                if (img.XResolution > img.YResolution)
                                {
                                    photoInfomation.DPI = img.YResolution;
                                }
                                else
                                {
                                    photoInfomation.DPI = img.XResolution;
                                }
                                //ImageDPI.ClassDPIClass aaa = new ImageDPI.ClassDPIClass();
                                //int DPI =aaa.GetImageDPIX(fileFullPath);
                                //if (_CheckDPI&&photoInfomation.DPI != DPI)
                                //{
                                //    MessageBox.Show(DateTime.Now + " 发现损坏文件：" + fileFullPath + Environment.NewLine, "提示",
                                //                                                      MessageBoxButtons.OK, MessageBoxIcon.Information);

                                //    continue;

                                //}
                            }
                            else
                            {
                                PhotoInfomation oldPhoto =
                               sizePhotoTemp.ListPhoto.FirstOrDefault(p => p.FullPath == fileFullPath);
                                photoInfomation.Width = oldPhoto.Width;
                                photoInfomation.Height = oldPhoto.Height;
                                photoInfomation.PhotoName = oldPhoto.PhotoName;
                                photoInfomation.FullPath = oldPhoto.FullPath;
                                photoInfomation.DPI = oldPhoto.DPI;
                                sizeNum.SizeIn = sizePhotoTemp.SizeIn;
                                sizeNum.SizeCm = sizePhotoTemp.SizeCm;
                                sizeNum.FlagRed = sizePhotoTemp.FlagRed;
                            }

                            SizeNum temp =
                                SizeKeyNum.FirstOrDefault(p => p.DirKey == sizeNum.DirKey && p.SizeIn == photoInfomation.SizeIn);


                            if (temp != null)
                            {
                                temp.Num++;
                                temp.ListPhoto.Add(photoInfomation);

                            }
                            else
                            {
                                sizeNum.ListPhoto = new List<PhotoInfomation>();
                                sizeNum.ListPhoto.Add(photoInfomation);
                                SizeKeyNum.Add(sizeNum);
                                ListSizeNum.Add(sizeNum);

                            }

                        }
                        else //处理文本文件
                        {

                            sizeNum.Num = 1;
                            sizeNum.SizeCm = "文本文件0X0";
                            sizeNum.SizeIn = "文本文件0X0";
                            sizeNum.ListPhoto = new List<PhotoInfomation>();
                            string fileName = fileFullPath.Substring(fileFullPath.LastIndexOf('\\') + 1);
                            sizeNum.ListPhoto = new List<PhotoInfomation>();
                            sizeNum.ListPhoto.Add(new PhotoInfomation() { DPI = 72, FullPath = fileFullPath, Height = 1, PhotoName = fileName, Width = 1 });
                            SizeKeyNum.Add(sizeNum);
                            ListSizeNum.Add(sizeNum);
                        }

                    }
                    else
                    {
                        #region//缓冲中取到Key目录重新选择的时候使用

                        SizeNum temp =
                            SizeKeyNum.FirstOrDefault(p => p.DirKey == sn.DirKey && p.SizeIn == sn.SizeIn);
                        if (temp != null) //列表中存在子项
                        {
                            PhotoInfomation pi = sn.ListPhoto.FirstOrDefault(p => p.FullPath == fileFullPath);

                            PhotoInfomation piNew = new PhotoInfomation();
                            piNew.FullPath = pi.FullPath;
                            piNew.Height = pi.Height;
                            piNew.Width = pi.Width;
                            piNew.DPI = pi.DPI;
                            piNew.PhotoName = pi.PhotoName;
                            temp.Num++;
                            temp.ListPhoto.Add(piNew);

                        }
                        else //列表中bu存在子项
                        {
                            sizeNum.DirKey = sn.DirKey;
                            sizeNum.FlagRed = sn.FlagRed;
                            sizeNum.Num = 1;
                            sizeNum.SizeCm = sn.SizeCm;
                            sizeNum.SizeIn = sn.SizeIn;
                            sizeNum.ListPhoto = new List<PhotoInfomation>();
                            PhotoInfomation pi = sn.ListPhoto.FirstOrDefault(p => p.FullPath == fileFullPath);

                            PhotoInfomation piNew = new PhotoInfomation();
                            piNew.FullPath = pi.FullPath;
                            piNew.Height = pi.Height;
                            piNew.Width = pi.Width;
                            piNew.DPI = pi.DPI;
                            piNew.PhotoName = pi.PhotoName;
                            sizeNum.ListPhoto.Add(piNew);
                            SizeKeyNum.Add(sizeNum);


                        }
                        #endregion

                    }


                    #endregion
                }
                else if (currDirLength <= intFloor)
                {
                    #region//实际目录不够显示用长

                    int EnoughNum = intFloor - currDirLength;
                    string dirKey = "";

                    if (fileFullPath.Substring(inDir.Length + 1).IndexOf('\\') != -1)
                    {
                        //点击目录以外的目录有照片
                        dirKey = (fileFullPath.Substring(inDir.Length + 1)).Substring(0,
                                                                                      (fileFullPath.Substring(
                                                                                          inDir.Length + 1)).
                                                                                          LastIndexOf('\\'));
                    }
                    else
                    {
                        //点击目录下的照片
                        dirKey = "<空>";
                    }



                    for (int i = 0; i < EnoughNum; i++)
                    {
                        dirKey = dirKey + "\\<空>";
                    }
                    sizeNum.DirKey = dirKey;
                    if (!fileFullPath.ToUpper().EndsWith(".TXT"))
                    {

                        SizeNum sn =
                            ListSizeNum.Where(
                                p =>
                                p.ListPhoto.Where(pt => pt.FullPath == fileFullPath).Count() > 0 && p.DirKey == dirKey)
                                .FirstOrDefault();

                        if (sn == null)
                        {
                            if (!isAutoAnlyse)
                            {
                                continue;
                            }


                            SizeNum sizePhotoTemp =
                                ListSizeNum.FirstOrDefault(p => p.ListPhoto.Count(pt => pt.FullPath == fileFullPath) > 0);

                            PhotoInfomation photoInfomation = new PhotoInfomation();
                            if (sizePhotoTemp == null)
                            {
                                CodecsImageInfo img = null;
                                try
                                {
                                    img = codecs.GetInformation(fileFullPath, true);
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show(DateTime.Now + " 发现损坏文件：" + fileFullPath + Environment.NewLine, "提示",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Information);

                                    continue;

                                }
                                float Width = (float)img.Width / img.XResolution;
                                float Height = (float)img.Height / img.YResolution;
                                string SizeCM = "";
                                string SizeInch = "";
                                if (Height > Width)
                                {
                                    SizeCM = string.Format("{0:0.##}", Height * 2.54) + "X" +
                                             string.Format("{0:0.##}", Width * 2.54) + "cm";
                                    SizeInch = string.Format("{0:0.##}", Height) + "X" +
                                               string.Format("{0:0.##}", Width) + "in";
                                }
                                else
                                {
                                    SizeCM = string.Format("{0:0.##}", Width * 2.54) + "X" +
                                             string.Format("{0:0.##}", Height * 2.54) + "cm";
                                    SizeInch = string.Format("{0:0.##}", Width) + "X" +
                                               string.Format("{0:0.##}", Height) + "in";
                                }
                                sizeNum.SizeIn = SizeInch;
                                sizeNum.SizeCm = SizeCM;
                                sizeNum.FlagRed = 0;

                                photoInfomation.Width = Width;
                                photoInfomation.Height = Height;
                                photoInfomation.PhotoName = img.Name;
                                photoInfomation.FullPath = fileFullPath;
                                if (img.XResolution > img.YResolution)
                                {
                                    photoInfomation.DPI = img.YResolution;
                                }
                                else
                                {
                                    photoInfomation.DPI = img.XResolution;
                                }
                                //ImageDPI.ClassDPIClass aaa = new ImageDPI.ClassDPIClass();
                                //int DPI = aaa.GetImageDPIX(fileFullPath);
                                //if (_CheckDPI && photoInfomation.DPI != DPI)
                                //{
                                //    MessageBox.Show(DateTime.Now + " 发现损坏文件：" + fileFullPath + Environment.NewLine, "提示",
                                //                                                      MessageBoxButtons.OK, MessageBoxIcon.Information);

                                //    continue;

                                //}
                            }
                            else
                            {
                                PhotoInfomation oldPhotoInfo = sizePhotoTemp.ListPhoto.FirstOrDefault(pt => pt.FullPath == fileFullPath);
                                photoInfomation.Width = oldPhotoInfo.Width;
                                photoInfomation.Height = oldPhotoInfo.Height;
                                photoInfomation.PhotoName = oldPhotoInfo.PhotoName;
                                photoInfomation.FullPath = oldPhotoInfo.FullPath;
                                photoInfomation.DPI = oldPhotoInfo.DPI;
                                sizeNum.SizeIn = sizePhotoTemp.SizeIn;
                                sizeNum.SizeCm = sizePhotoTemp.SizeCm;
                                sizeNum.FlagRed = sizePhotoTemp.FlagRed;
                            }

                            SizeNum temp =
                                SizeKeyNum.FirstOrDefault(p => p.DirKey == sizeNum.DirKey && p.SizeIn == photoInfomation.SizeIn);

                            if (temp != null)
                            {
                                temp.Num++;
                                temp.ListPhoto.Add(photoInfomation);

                            }
                            else
                            {
                                sizeNum.ListPhoto = new List<PhotoInfomation>();
                                sizeNum.ListPhoto.Add(photoInfomation);
                                SizeKeyNum.Add(sizeNum);
                                ListSizeNum.Add(sizeNum);

                            }
                        }
                        else
                        {

                            SizeNum temp =
                                SizeKeyNum.FirstOrDefault(p => p.DirKey == sn.DirKey && p.SizeIn == sn.SizeIn);
                            if (temp != null) //列表中存在子项
                            {
                                PhotoInfomation pi = sn.ListPhoto.FirstOrDefault(p => p.FullPath == fileFullPath);

                                PhotoInfomation piNew = new PhotoInfomation();
                                piNew.FullPath = pi.FullPath;
                                piNew.Height = pi.Height;
                                piNew.Width = pi.Width;
                                piNew.DPI = pi.DPI;
                                piNew.PhotoName = pi.PhotoName;
                                temp.Num++;
                                temp.ListPhoto.Add(piNew);

                            }
                            else //列表中bu存在子项
                            {
                                sizeNum.DirKey = sn.DirKey;
                                sizeNum.FlagRed = sn.FlagRed;
                                sizeNum.Num = 1;
                                sizeNum.SizeCm = sn.SizeCm;
                                sizeNum.SizeIn = sn.SizeIn;
                                sizeNum.ListPhoto = new List<PhotoInfomation>();
                                PhotoInfomation pi = sn.ListPhoto.FirstOrDefault(p => p.FullPath == fileFullPath);

                                PhotoInfomation piNew = new PhotoInfomation();
                                piNew.FullPath = pi.FullPath;
                                piNew.Height = pi.Height;
                                piNew.Width = pi.Width;
                                piNew.DPI = pi.DPI;
                                piNew.PhotoName = pi.PhotoName;
                                sizeNum.ListPhoto.Add(piNew);
                                SizeKeyNum.Add(sizeNum);


                            }
                        }

                    }

                    else //处理文本文件
                    {

                        sizeNum.Num = 1;
                        sizeNum.SizeCm = "文本文件0X0";
                        sizeNum.SizeIn = "文本文件0X0";
                        SizeKeyNum.Add(sizeNum);
                        string fileName = fileFullPath.Substring(fileFullPath.LastIndexOf('\\') + 1);
                        sizeNum.ListPhoto = new List<PhotoInfomation>();
                        sizeNum.ListPhoto.Add(new PhotoInfomation() { DPI = 72, FullPath = fileFullPath, Height = 1, PhotoName = fileName, Width = 1 });
                        ListSizeNum.Add(sizeNum);
                    }




                    #endregion
                }
                else if (currDirLength == 0)
                {

                }


            }
            return SizeKeyNum.OrderBy(p => p.DirKey).ToList();
        }


        private void gridViewListView_CellMerge(object sender, CellMergeEventArgs e)
        {
            int columnNum = 0;
            //for (int i = 0; i < gridViewListView.Columns.Count; i++)
            //{
            //    if (e.Column.Name == gridViewListView.Columns[i].Name)
            //    {
            //        columnNum = i;
            //    }
            //}

            columnNum = e.Column.AbsoluteIndex;


            if (columnNum < intGFloor)
            {

                if (IsMerge(e.RowHandle1, e.RowHandle2, columnNum))
                {
                    e.Merge = true;
                    e.Handled = true;
                }
                else
                {
                    //e.Merge = false;
                    e.Handled = true;
                }
            }
            else
            {
                e.Handled = true;
            }

        }

        private bool IsMerge(int inRowNum1, int inRowNum2, int curColumnIndex)
        {
            bool rtnBool = true;
            //for (int i = 0; i < inEndColNum; i++)
            //{
            for (int i = curColumnIndex; i >= 0; i--)
            {
                string value1 = Convert.ToString(gridViewListView.GetRowCellValue(inRowNum1, gridViewListView.Columns[i]));
                string value2 = Convert.ToString(gridViewListView.GetRowCellValue(inRowNum2, gridViewListView.Columns[i]));
                if (value1.Equals(value2))
                {
                    continue;
                }
                else
                {
                    rtnBool = false;
                    break;
                }

            }
            //if (inEndColNum == 0)
            //{
            //    string value1 = Convert.ToString(gridViewListView.GetRowCellValue(inRowNum1, gridViewListView.Columns[inEndColNum]));
            //    string value2 = Convert.ToString(gridViewListView.GetRowCellValue(inRowNum2, gridViewListView.Columns[inEndColNum]));
            //    if (value1.Equals(value2))
            //    {
            //        rtnBool = true;
            //    }
            //    else
            //    {
            //        rtnBool = false;

            //    }
            //}
            return rtnBool;
        }

        private void toolStripTextBoxDisplayFloor_Leave(object sender, EventArgs e)
        {
            try
            {
                Convert.ToInt32(toolStripTextBoxDisplayFloor.Text);
            }
            catch (Exception)
            {

                MessageBox.Show("显示层数应为数字", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Properties.Settings.Default.IntFloorNum = Convert.ToInt32(toolStripTextBoxDisplayFloor.Text);
            Properties.Settings.Default.Save();
        }
        [DllImport("shell32.dll ")]
        private static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);

        private void toolStripButtonExport_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|pdf(*.pdf)|*.pdf|电子表格(*.xls)|*.xls|html(*.html)|*.html";
            //saveFileDialog.AddExtension = true;
            saveFileDialog.FilterIndex = 3;
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileName = saveFileDialog.FileName;
                if (saveFileDialog.OpenFile() != null)
                {
                    switch (saveFileDialog.FilterIndex)
                    {
                        case 3:
                            XlsExportOptions xlsOptions = new XlsExportOptions(false);
                            gridControlView.ExportToXls(fileName, xlsOptions);
                            break;
                        case 4:
                            gridControlView.ExportToHtml(fileName);
                            break;
                        case 2:
                            gridControlView.ExportToPdf(fileName);
                            break;
                        case 1:
                            this.gridControlView.ExportToText(fileName);
                            break;
                        default:
                            break;
                    }
                }

            }
            MessageBox.Show("导出完成", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private bool IsAutoAnlyse = true;
        private void toolStripButtonAutoAnlyse_Click(object sender, EventArgs e)
        {
            if (IsAutoAnlyse)
            {
                IsAutoAnlyse = !IsAutoAnlyse;
                toolStripButtonAutoAnlyse.Text = "开启自动分析";
            }
            else
            {
                IsAutoAnlyse = !IsAutoAnlyse;
                toolStripButtonAutoAnlyse.Text = "关闭自动分析";
            }
        }

        private void gridViewListView_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                DataRowView row = (DataRowView)gridViewListView.GetRow(e.RowHandle);
                if (e.Column.Name == "Link") //连动显示照片详情
                {


                    //ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                    //                         new StringBuilder(row["Path"].ToString()), new StringBuilder(string.Empty), 1);

                    if (row != null && row["Path"] != null)
                    {
                        string openPath = row["Path"].ToString();
                        //browser1.SelectedNode = new TreeNode("openPath");
                        browser1.SelectPath(openPath, true);
                        List<PhotoInfomation> listPhoto =
                            ListSizeNum.FirstOrDefault(
                                p =>
                                p.DirKey.Equals(row["DirKey"].ToString()) && p.SizeIn.Equals(row["SizeIn"].ToString())).
                                ListPhoto.ToList();
                        gridControlPhotoInfo.DataSource = listPhoto;
                        gridControlPhotoInfo.RefreshDataSource();
                    }


                }
                if (e.Clicks == 2)
                {
                    try
                    {

                        this.Cursor = Cursors.WaitCursor;
                        int currColID = 0;
                        for (int i = 0; i < gridViewListView.Columns.Count; i++)
                        {
                            if (i < Properties.Settings.Default.IntFloorNum)
                            {
                                if (gridViewListView.Columns[i].Name == e.Column.Name)
                                {
                                    currColID = i; //找到列
                                    break;
                                }
                            }

                        }

                        string currPath = CurrSelectPath.Replace(StartOrderTotalPath, "V:");
                        for (int i = 0; i <= currColID; i++)
                        {
                            if (row[i].ToString().IndexOf("空") == -1)
                            {
                                currPath = currPath + "\\" + row[i].ToString();
                            }
                        }
                        browser1.SelectPath(currPath, true);
                    }
                    catch (Exception exxx)
                    {


                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                    }

                }
            }
        }

        private void gridViewListView_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridViewListView_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            //if (e.RowHandle >= 0)
            //{
            //    DataRowView row = (DataRowView)gridViewListView.GetRow(e.RowHandle);
            //    List<PhotoInfomation> listPhoto =
            //                ListSizeNum.FirstOrDefault(
            //                    p =>
            //                    p.DirKey.Equals(row["DirKey"].ToString()) && p.SizeIn.Equals(row["SizeIn"].ToString())).
            //                    ListPhoto.ToList();
            //    gridControlPhotoInfo.DataSource = listPhoto;
            //    gridControlPhotoInfo.RefreshDataSource();
            //}
        }

        private void toolStripButtonRushCurrFolder_Click(object sender, EventArgs e)
        {
            List<string> FileList = new List<string>();

            GetAllPicByDir(CurrSelectPath, FileList);
            foreach (string str in FileList)
            {
                ListSizeNum.Remove(
                    ListSizeNum.FirstOrDefault(p => p.ListPhoto.Where(pt => pt.FullPath == str).Count() > 0));
            }
            DisplayTables(true);


        }

        private void gridViewListView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {

                DataRowView row = (DataRowView)gridViewListView.GetRow(e.RowHandle);

                //ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                //                         new StringBuilder(row["Path"].ToString()), new StringBuilder(string.Empty), 1);
                if (row != null && row["FlagRed"] != null)
                {
                    int Flag = Convert.ToInt32(row["FlagRed"].ToString());
                    //browser1.SelectedNode = new TreeNode("openPath");
                    if (Flag == 1)
                    {
                        if (e.Column.AbsoluteIndex >= intGFloor)
                        {
                            e.Appearance.BackColor = Color.LightPink;
                        }
                    }



                }

            }
        }

        private void toolStripButtonBack_Click(object sender, EventArgs e)
        {
            browser1.BrowserBack();
        }

        private void toolStripButtonUp_Click(object sender, EventArgs e)
        {
            browser1.BrowserUp();
        }

        private void gridViewListView_RowClick(object sender, RowClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                DataRowView row = (DataRowView)gridViewListView.GetRow(e.RowHandle);
                List<PhotoInfomation> listPhoto =
                            ListSizeNum.FirstOrDefault(
                                p =>
                                p.DirKey.Equals(row["DirKey"].ToString()) && p.SizeIn.Equals(row["SizeIn"].ToString())).
                                ListPhoto.ToList();
                gridControlPhotoInfo.DataSource = listPhoto;
                gridControlPhotoInfo.RefreshDataSource();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (toolStripButton1.Text.Equals("开启检查尺寸"))
            {
                Properties.Settings.Default.CheckDPI = false;
                toolStripButton1.Text = "关闭检查尺寸";
                Properties.Settings.Default.Save();
                _CheckDPI = false;
            }
            else
            {
                Properties.Settings.Default.CheckDPI = true;
                toolStripButton1.Text = "开启检查尺寸";
                Properties.Settings.Default.Save();
                _CheckDPI = true;
            }
        }
        bool _CheckDPI = false;





    }
    public class SizeNum
    {
        public string DirKey { get; set; }
        public string SizeIn { get; set; }
        public string SizeCm { get; set; }

        public int Num { get; set; }
        public List<PhotoInfomation> ListPhoto { get; set; }
        public int FlagRed { get; set; }
    }
    public class UnitCell
    {
        //public Point CellPosition { get; set; }
        //public string Flag { get; set; }//Flag S开始M中间E结束
        public string CellValue { get; set; }
        public Point StartPosition { get; set; }
        public Point EndPosition { get; set; }
    }
    public class PhotoInfomation
    {
        public float Width { get; set; }
        public float Height { get; set; }
        public string PhotoName { get; set; }
        public string FullPath { get; set; }
        public int DPI { get; set; }
        //string SizeCM = "";
        //                    string SizeInch = "";
        //                    if (this.Height > this.Width)
        //                    {
        //                        SizeCM = string.Format("{0:0.##}", Height * 2.54) + "X" +
        //                                 string.Format("{0:0.##}", Width * 2.54) + "cm";
        //                        SizeInch = string.Format("{0:0.##}", Height) + "X" +
        //                                   string.Format("{0:0.##}", Width) + "in";
        //                    }
        //                    else
        //                    {
        //                        SizeCM = string.Format("{0:0.##}", Width * 2.54) + "X" +
        //                                 string.Format("{0:0.##}", Height * 2.54) + "cm";
        //                        SizeInch = string.Format("{0:0.##}", Width) + "X" +
        //                                   string.Format("{0:0.##}", Height) + "in";
        //                    }
        public string SizeCM
        {
            get
            {
                if (this.Height > this.Width)
                {
                    return string.Format("{0:0.##}", Height * 2.54) + "X" +
                              string.Format("{0:0.##}", Width * 2.54) + "cm";

                }
                else
                {
                    return string.Format("{0:0.##}", Width * 2.54) + "X" +
                              string.Format("{0:0.##}", Height * 2.54) + "cm";

                }
            }
        }
        public string SizeIn
        {
            get
            {
                if (this.Height > this.Width)
                {
                    return string.Format("{0:0.##}", Height) + "X" +
                                                   string.Format("{0:0.##}", Width) + "in";

                }
                else
                {
                    return string.Format("{0:0.##}", Width) + "X" +
                                 string.Format("{0:0.##}", Height) + "in";
                }
            }
        }
    }
}
